package com.haiyi.software.app;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import kankan.wheel.widget.WheelView;

import android.R.integer;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.haiyi.software.app.R.string;
import com.haiyi.software.app.basic.ActivityMineBasicDelAttch;
import com.haiyi.software.app.basic.ActivityMineBasicMenu;
import com.haiyi.software.app.basic.ActivityMineBasicSetHead;
import com.haiyi.software.entity.EntityUserPhoto;
import com.haiyi.software.mycontrols.MyControlListTitle;
import com.haiyi.software.tools.L;
import com.haiyi.software.tools.MyTools;
import com.haiyi.software.xmpp.event.XMPPConnectionState;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshScrollView;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;

public class ActivityMine extends ActivityMineBasicSetHead implements
		OnClickListener {

	private static final int TAKE_BIG_PICTURE = 1;
	private static final int TAKE_SMALL_PICTURE = 2;
	private static final int CROP_BIG_PICTURE = 3;
	private static final int CROP_SMALL_PICTURE = 4;
	private static final int CHOOSE_BIG_PICTURE = 5;
	private static final int CHOOSE_SMALL_PICTURE = 6;
	private static final int CHOOSE_BIG_PICTURE_FM = 7;
	private static final int TAKE_BIG_PICTURE_FM = 8;
	public static final int SHOW_SUB_ACTIVITY_MODIFYUSERINFO = 9;
	private static final int CROP_BIG_PICTURE_FM = 10;
	public static final int UPDATE_USER_SIGN_SUCCESS = 11;

	private final String TAG = "FragmentPersonal";

	private DisplayImageOptions options, options_fm;

	private ImageLoader imageLoader;

	private GridView gridViewImgList;

	private List<Map<String, EntityUserPhoto>> list;

	private MyControlListTitle controlListTitle;

	private TextView textView_personalName;

	private TextView textView_sex;

	private TextView textView_constellation;

	private TextView textView_golds;

	private ImageView img_goldsmore;

	private TextView textview_vgold;

	private TextView textview_uid;

	private TextView textview_uname;

	private TextView textview_usex;

	private TextView textview_ubody;

	private TextView textview_birthday;

	private TextView textview_ujob;

	private TextView textview_income;

	private TextView textview_mynews;

	private ImageView img_newsmore;

	private ImageView img_gifssmore;

	private Button btn_goto_recharge;

	private Button btn_goto_charmCity;

	private Button btn_myGifts, btn_mySay;

	private MyAdapter mydpt;

	private PullToRefreshScrollView pull_refresh_scrollview;

	private String IMAGE_FILE_LOCATION = null;
	private Uri imageUri;// to store the big bitmap

	private ImageView img_person_head;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO 自动生成的方法存根
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_mine);

		list = new ArrayList<Map<String, EntityUserPhoto>>();

		initComp();

		mydpt = new MyAdapter(this);

		handlerLoad.sendEmptyMessageDelayed(1, 300);
	}

	Handler handlerLoad = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			// TODO 自动生成的方法存根
			super.handleMessage(msg);
			pull_refresh_scrollview.setRefreshing();
		}

	};

	private void initComp() {

		DisplayMetrics metric = new DisplayMetrics();

		getWindowManager().getDefaultDisplay().getMetrics(metric);

		int width = metric.widthPixels; // 屏幕宽度（像素）
		// int height = metric.heightPixels; // 屏幕高度（像素）

		L.i("width=" + width);

		img_person_head = (ImageView) this.findViewById(R.id.img_person_head);

		LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, width);

		img_person_head.setLayoutParams(params);

		pull_refresh_scrollview = (PullToRefreshScrollView) this
				.findViewById(R.id.pull_refresh_scrollview);

		controlListTitle = (MyControlListTitle) this
				.findViewById(R.id.list_title);

		textView_personalName = (TextView) this
				.findViewById(R.id.textView_personalName);

		textview_birthday = (TextView) this
				.findViewById(R.id.textview_birthday);

		textView_constellation = (TextView) this
				.findViewById(R.id.textView_constellation);

		textview_vgold = (TextView) this.findViewById(R.id.textview_vgold);

		textView_golds = (TextView) this.findViewById(R.id.textView_golds);

		textview_income = (TextView) this.findViewById(R.id.textview_income);

		textview_mynews = (TextView) this.findViewById(R.id.textview_mynews);

		textView_sex = (TextView) this.findViewById(R.id.textView_sex);

		textview_ubody = (TextView) this.findViewById(R.id.textview_ubody);

		textview_uid = (TextView) this.findViewById(R.id.textview_uid);

		textview_ujob = (TextView) this.findViewById(R.id.textview_ujob);

		textview_uname = (TextView) this.findViewById(R.id.textview_uname);

		textview_usex = (TextView) this.findViewById(R.id.textview_usex);

		img_gifssmore = (ImageView) this.findViewById(R.id.img_gifssmore);

		img_goldsmore = (ImageView) this.findViewById(R.id.img_goldsmore);

		// img_newsmore = (ImageView) this.findViewById(R.id.img_newsmore);

		btn_goto_recharge = (Button) this.findViewById(R.id.btn_goto_recharge);

		btn_goto_charmCity = (Button) this
				.findViewById(R.id.btn_goto_charmCity);

		btn_myGifts = (Button) this.findViewById(R.id.btn_myGifts);

		btn_mySay = (Button) this.findViewById(R.id.btn_mySay);

		btn_goto_recharge.setOnClickListener(this);
		btn_goto_charmCity.setOnClickListener(this);
		btn_mySay.setOnClickListener(this);
		btn_myGifts.setOnClickListener(this);

		// controlListTitle.setText("我人金币");
		// 图片控件*********************************************
		imageLoader = ImageLoader.getInstance();
		options = new DisplayImageOptions.Builder()
				.imageScaleType(ImageScaleType.EXACTLY_STRETCHED)
				.showImageOnLoading(R.drawable.ic_launcher)
				.showImageForEmptyUri(R.drawable.ic_launcher)
				.showImageOnFail(R.drawable.ic_launcher).cacheInMemory(true)
				.cacheOnDisc(true).considerExifParams(true)
				.displayer(new RoundedBitmapDisplayer(10)).build();

		options_fm = new DisplayImageOptions.Builder()
				.imageScaleType(ImageScaleType.EXACTLY_STRETCHED)
				.showImageOnLoading(R.drawable.mv)
				.showImageForEmptyUri(R.drawable.mv)
				.showImageOnFail(R.drawable.mv).cacheInMemory(true)
				.cacheOnDisc(true).considerExifParams(true)
				.displayer(new RoundedBitmapDisplayer(0)).build();
		// *****************************************************

		this.gridViewImgList = (GridView) this
				.findViewById(R.id.gridview_personImgList);

		//
		// 右上角按钮
		final Button button = (Button) this.findViewById(R.id.nextBtn_username);

		button.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				// TODO 自动生成的方法存根
				showMenu(ActivityMine.this, button);
			}
		});
		// TODO 自动生成的方法存根

		pull_refresh_scrollview.setOnRefreshListener(RefreshListener);

		img_person_head.setOnLongClickListener(longClickListener);
	}

	private View.OnLongClickListener longClickListener = new View.OnLongClickListener() {

		@Override
		public boolean onLongClick(View v) {

			takeImage(300, 300, CHOOSE_BIG_PICTURE_FM, TAKE_BIG_PICTURE_FM);

			return false;
		}
	};

	private OnRefreshListener<ScrollView> RefreshListener = new OnRefreshListener<ScrollView>() {

		@Override
		public void onRefresh(PullToRefreshBase<ScrollView> refreshView) {
			// TODO 自动生成的方法存根
			requestNetworkData();
		}
	};

	private class MyAdapter extends BaseAdapter {

		private Context context;

		private LayoutInflater inflater;

		public MyAdapter(Context context) {

			this.context = context;
			this.inflater = LayoutInflater.from(context);

		}

		@Override
		public int getCount() {

			// TODO 自动生成的方法存根
			if (list.size() < 8) {

				return list.size() + 1;
			} else {
				return list.size();
			}

		}

		@Override
		public Object getItem(int position) {

			// TODO 自动生成的方法存根

			return list.get(position);
		}

		@Override
		public long getItemId(int position) {

			// TODO 自动生成的方法存根
			return position;
		}

		@Override
		public View getView(final int position, View convertView,
				ViewGroup parent) {

			ViewHolder viewHolder = null;
			// if (convertView == null) {
			convertView = inflater.inflate(R.layout.item_imglist, null);
			viewHolder = new ViewHolder();

			viewHolder.imgHolder = (ImageView) convertView
					.findViewById(R.id.img_personImgList);

			viewHolder.btnImg = (Button) convertView
					.findViewById(R.id.item_n_btn);

			convertView.setTag(viewHolder);
			// } else {
			// viewHolder = (ViewHolder) convertView.getTag();

			// viewHolder.imgHolder.setImageDrawable(null);
			// }

			if (position < list.size()) {

				imageLoader.displayImage(list.get(position).get("itemPhoto")
						.getPhosmall(), viewHolder.imgHolder, options);

				viewHolder.btnImg.setTag(list.get(position).get("itemPhoto")
						.getAttuid());

				viewHolder.btnImg.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO 自动生成的方法存根
						startImagePagerActivity(position);
					}
				});

				viewHolder.btnImg.setOnLongClickListener(imgLongClickListener);

			}

			if (position == list.size()) {
				viewHolder.imgHolder.setImageDrawable(getResources()
						.getDrawable(R.drawable.personphotoadd));

				viewHolder.btnImg.setOnClickListener(imgUploadClick);

			}

			// TODO 自动生成的方法存根
			return convertView;
		}
	}

	private OnLongClickListener imgLongClickListener = new OnLongClickListener() {

		private String[] str_menu = { "设置为头像", "删除头像" };

		@Override
		public boolean onLongClick(final View v) {

			Builder builder = new AlertDialog.Builder(ActivityMine.this);

			builder.setIcon(null);

			builder.setTitle(null);

			builder.setItems(str_menu, new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO 自动生成的方法存根
					switch (which) {
					case 0:

						setHeadByAttID(v.getTag().toString());

						break;

					case 1:

						deleteAttchByID(v.getTag().toString());

						break;

					}
				}
			});

			builder.show();

			return true;
		}
	};

	private void startImagePagerActivity(int position) {
		Intent intent = new Intent(this, ImagePagerActivity.class);

		intent.putExtra("images", (Serializable) list);
		intent.putExtra("position", position);
		startActivity(intent);
	}

	/**
	 * 上传图片
	 */
	private View.OnClickListener imgUploadClick = new OnClickListener() {

		@Override
		public void onClick(View v) {

			takeImage(300, 300, CHOOSE_BIG_PICTURE, TAKE_BIG_PICTURE);

		}
	};

	/**
	 * 获取图片
	 */
	private void takeImage(final int width, final int height,
			final int PICTURE, final int CAPTURE) {

		String[] items = { "从相册选择图片", "从相机拍摄图片" };
		// TODO 自动生成的方法存根
		Builder builder = new AlertDialog.Builder(ActivityMine.this);

		builder.setIcon(null);

		builder.setTitle(null);

		builder.setItems(items, new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {

				Intent intent = null;
				imageUri = Uri.parse("file://"
						+ MainApplication.getInstance().getAppFaceDirectory()
						+ "/" + System.currentTimeMillis() + ".jpg");
				switch (which) {
				case 0:

					L.i("src", imageUri.getPath());

					intent = new Intent(Intent.ACTION_GET_CONTENT, null);
					intent.setType("image/*");
					intent.putExtra("crop", "true");
					intent.putExtra("aspectX", 1);
					intent.putExtra("aspectY", 1);
					intent.putExtra("outputX", width);
					intent.putExtra("outputY", height);
					intent.putExtra("scale", true);
					intent.putExtra("return-data", false);
					intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
					intent.putExtra("outputFormat",
							Bitmap.CompressFormat.JPEG.toString());
					intent.putExtra("noFaceDetection", false);
					startActivityForResult(intent, PICTURE);

					break;
				case 1:

					intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
					intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
					startActivityForResult(intent, CAPTURE);
					break;
				default:
					break;
				}
			}
		});
		builder.show();
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {

		// TODO 自动生成的方法存根

		// super.onActivityResult(requestCode, resultCode, data);
		String result = data != null ? data.toString() : "没有图片";
		// 关闭后返回的数据
		L.i(TAG, requestCode + ":" + resultCode + result);

		switch (requestCode) {

		case TAKE_BIG_PICTURE_FM:

			cropImageUri(imageUri, 300, 300, CROP_BIG_PICTURE_FM);

			break;

		case TAKE_BIG_PICTURE:

			cropImageUri(imageUri, 300, 300, CROP_BIG_PICTURE);

			break;
		case CHOOSE_BIG_PICTURE:

			if (imageUri != null) {

				UpImg(imageUri, 1);
			}
			break;

		case CHOOSE_BIG_PICTURE_FM:

			if (imageUri != null) {

				UpImg(imageUri, 4);
			}
			break;
		case CROP_BIG_PICTURE:

			UpImg(imageUri, 1);

			break;
		case CROP_BIG_PICTURE_FM:

			UpImg(imageUri, 4);

			break;
		case 10010:
			requestNetworkData();
			break;

		case 10011:
			requestNetworkData();
			break;

		}
		switch (resultCode) {

		case SHOW_SUB_ACTIVITY_MODIFYUSERINFO:

			handlerLoad.sendEmptyMessageDelayed(1, 300);
			break;

		case UPDATE_USER_SIGN_SUCCESS:

			handlerLoad.sendEmptyMessageDelayed(1, 300);

			break;

		}
	}

	private void UpImg(Uri uri, int type) {

		UploadImage(uri.getPath(), type);
	}

	private void cropImageUri(Uri uri, int outputX, int outputY, int requestCode) {
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, "image/*");
		intent.putExtra("crop", "true");
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		intent.putExtra("outputX", outputX);
		intent.putExtra("outputY", outputY);
		intent.putExtra("scale", true);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
		intent.putExtra("return-data", false);
		intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
		intent.putExtra("noFaceDetection", true); // no face detection
		startActivityForResult(intent, requestCode);
	}

	private static class ViewHolder {

		ImageView imgHolder;
		Button btnImg;
	}

	private MyTools tools = MyTools.getInstance();

	@Override
	public void requestFinish(JsonObject jsonObjectReturn) {
		// TODO 自动生成的方法存根
		textView_personalName.setText(mapUser.get("username") != null ? mapUser
				.get("username").toString() : "");

		textView_sex.setBackgroundResource(tools.getSexBackground(mapUser.get(
				"usex").toString()));

		textView_sex.setText(mapUser.get("age") != null ? mapUser.get("age")
				.toString() : "");

		textView_sex.setGravity(Gravity.CENTER_VERTICAL);

		textView_sex.setPadding(40, 2, 5, 0);

		textview_birthday.setText(mapUser.get("ubirthday") != null ? mapUser
				.get("ubirthday").toString() : "");

		textview_ubody.setText(mapUser.get("ubody") != null ? mapUser.get(
				"ubody").toString() : "");

		// textview_theGiftsGolds.setText("")

		textView_golds.setText(mapUser.get("gold") != null ? mapUser
				.get("gold").toString() : "");

		textview_income.setText(mapUser.get("umoney") != null ? mapUser.get(
				"umoney").toString() : "");

		textview_ujob.setText(mapUser.get("uwork") != null ? mapUser.get(
				"uwork").toString() : "");

		textview_uid.setText(mapUser.get("uid") != null ? mapUser.get("uid")
				.toString() : "");

		textview_uname.setText(mapUser.get("uname") != null ? mapUser.get(
				"uname").toString() : "");

		textview_mynews
				.setText(mapUser.get("sign").toString().length() > 0 ? mapUser
						.get("sign").toString() : "未填写");

		textview_vgold.setText(mapUser.get("vgold") != null ? mapUser.get(
				"vgold").toString() : "0");

		textview_usex.setText(MyTools.getInstance().getSexNameBySexID(
				mapUser.get("usex").toString()));

		textView_constellation.setText(mapUser.get("ustar") != null ? mapUser
				.get("ustar").toString() : "");

		imageLoader.displayImage(str_server
				+ MainApplication.getInstance().getMineUserInfo().getuCover(),
				img_person_head, options_fm);

		// 加载图片地址*****************************

		JsonArray headAry = (JsonArray) mapUser.get("uhead");

		Map<String, EntityUserPhoto> map = null;

		if (headAry.size() > 0) {

			list.clear();

			for (JsonElement item : headAry) {

				map = new HashMap<String, EntityUserPhoto>();

				EntityUserPhoto userPhoto = new EntityUserPhoto();

				userPhoto.setAttuid(item.getAsJsonObject().get("attuid")
						.getAsString());

				userPhoto.setPhobig(str_server
						+ item.getAsJsonObject().get("phobig").getAsString());

				userPhoto.setPhosmall(str_server
						+ item.getAsJsonObject().get("phosmall").getAsString());

				map.put("itemPhoto", userPhoto);

				list.add(map);
			}

		} else {
			// friend.setUfPhoto("");
		}
		// ***************************************

		gridViewImgList.setAdapter(mydpt);

		pull_refresh_scrollview.onRefreshComplete();
	}

	@Override
	/**
	 * 上传图片成功后
	 */
	protected void UploadImageSuccess() {

		watingDialog.cancel();

		String str_state = jsonReturn.get("state").getAsString();

		Toast.makeText(this, jsonReturn.get("desc").getAsString(),
				Toast.LENGTH_LONG).show();

		// if (str_state.equals("200") || str_state.equals("202")) {

		requestNetworkData();
		// }
	}

	@Override
	public void onClick(View v) {
		// TODO 自动生成的方法存根
		switch (v.getId()) {
		case R.id.btn_goto_recharge:

			Intent intent = new Intent();

			intent.setClass(ActivityMine.this, ActivityRecharge.class);

			startActivityForResult(intent, 10010);

			break;
		case R.id.btn_goto_charmCity:

			Intent intent2 = new Intent();

			intent2.setClass(ActivityMine.this, ActivityCharmCityList.class);

			startActivityForResult(intent2, 10011);
			break;

		case R.id.btn_myGifts:

			Intent intent3 = new Intent();

			intent3.setClass(ActivityMine.this, ActivityMyGiftList.class);

			startActivity(intent3);
			break;

		case R.id.btn_mySay:

			Intent intent4 = new Intent();

			intent4.setClass(ActivityMine.this, ActivityMySay.class);

			intent4.putExtra("sign", textview_mynews.getText().toString());

			startActivityForResult(intent4, UPDATE_USER_SIGN_SUCCESS);

			break;
		}
	}

	@Override
	protected void deleteAttchByIdSuccess(String strReturn) {
		// TODO 自动生成的方法存根
		try {

			JsonParser parser = new JsonParser();

			JsonObject object = parser.parse(strReturn).getAsJsonObject();

			Toast.makeText(ActivityMine.this, object.get("desc").getAsString(),
					Toast.LENGTH_LONG).show();

			requestNetworkData();

		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	@Override
	protected void setHeadSuccess(String strReturn) {
		// TODO 自动生成的方法存根
		try {

			JsonParser parser = new JsonParser();

			JsonObject object = parser.parse(strReturn).getAsJsonObject();

			Toast.makeText(ActivityMine.this, object.get("desc").getAsString(),
					Toast.LENGTH_LONG).show();

			requestNetworkData();

		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	@Override
	protected void requestError() {

		pull_refresh_scrollview.onRefreshComplete();
		Toast.makeText(ActivityMine.this, "网络连接错误", Toast.LENGTH_LONG).show();
	}

}
